﻿// <copyright file="ClassLvlMethodReport.aspx.cs">
// Copyright (c) 2009 All Right Reserved
// </copyright>
// <author>Yuvaraj Ilangovan</author>
// <date>2009-07-14</date>
// <summary>Contains UI logic for showing class and method level reports</summary>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RepRef;
using System.Data;
using System.Configuration;

public partial class ContentPages_ClassLvlMethodReport : System.Web.UI.Page
{
    RepRef.IsimpleWcfClient aggrProxy;
    RepRef.StatisticsReport ststReport;
    RepRef.ModuleManager mgr;
    IList<RepRef.MethodInfo> MtdInfoCollection = null;
    IList<RepRef.ClassMethodInfoAggr> ClsMtdInfoCollection = null;
    string strXMLPath;
    public static bool showImage = false;
    IList<LineItem> LnInfoColln = null;

    public string ProjectName
    {
        get
        {
            string _projName = string.Empty;
            if (Session["ProjName"] != null)
            {
                _projName = Convert.ToString(Session["ProjName"]);
            }
            else
            {
                _projName = ConfigurationManager.AppSettings["ProjName"].ToString();
            }
            return _projName;
        }
    }


    protected void Page_Load(object sender, EventArgs e)
    {
        lblprojName.Text = this.ProjectName; 
        if (Session["RptXMLPath"] != null)
        {
            strXMLPath = Session["RptXMLPath"].ToString();
        }
        string modName = string.Empty;
        string nsName = string.Empty;
        string clsName = string.Empty;

        if (Request.QueryString != null)
        {
            ViewState["LnInfoColn"] = null;
            if ((!string.IsNullOrEmpty(Request.QueryString["nName"])) && (!string.IsNullOrEmpty(Request.QueryString["mod1"])) && (!string.IsNullOrEmpty(Request.QueryString["clsName"])))
            {
                modName = Request.QueryString["mod1"].ToString();
                nsName = Request.QueryString["nName"].ToString();
                clsName = Request.QueryString["clsName"].ToString();
                aggrProxy = new IsimpleWcfClient();
                LnInfoColln = aggrProxy.GetLineInfo(modName, nsName, clsName, strXMLPath);
                ViewState["LnInfoColn"] = LnInfoColln;
            }
        }
        if (!IsPostBack)
        {
            if (Request.QueryString != null)
            {
                if ((!string.IsNullOrEmpty(Request.QueryString["nName"])) && (!string.IsNullOrEmpty(Request.QueryString["mod1"])) && (!string.IsNullOrEmpty(Request.QueryString["clsName"])))
                {
                    LoadClassLvlStatistics(Request.QueryString["mod1"].ToString(), Request.QueryString["nName"].ToString(), Request.QueryString["clsName"].ToString(), strXMLPath);
                    //
                    //PopulateClassMethodCoverage(Request.QueryString["mod1"].ToString(), Request.QueryString["nName"].ToString(), Request.QueryString["clsName"].ToString(), strXMLPath);
                    LoadClsLvlMtdAggReport(Request.QueryString["mod1"].ToString(), Request.QueryString["nName"].ToString(), Request.QueryString["clsName"].ToString(), strXMLPath);
                    //LoadFileCode(Request.QueryString["mod1"].ToString(), Request.QueryString["nName"].ToString(), Request.QueryString["clsName"].ToString(), strXMLPath);
                }
            }

        }
    }

    protected void LoadClassLvlStatistics(string modName, string nsName, string clsName, string strXMLPath)
    {
        try
        {
            aggrProxy = new IsimpleWcfClient();
            mgr = aggrProxy.ParseXmlObject(strXMLPath);
            ststReport = aggrProxy.GetStateticsByClass(modName, nsName, clsName, strXMLPath);           
            lblCovLines.Text = ststReport.LOC.ToString();
            lblParCovLines.Text = ststReport.PLOC.ToString();
            lblCovBlocks.Text = ststReport.BlocksCov.ToString();
            lblNCLines.Text = ststReport.NCLOC.ToString();
            lblNCBlocks.Text = ststReport.BlocksNt.ToString();
            lblStatsName.Text = clsName;
            //lblCovClasses.Text = ststReport.TotClsCov.ToString();
            lblLnsMtd.Text = string.Format("{0:#.##}", ststReport.AvgLnsMtd);
            lblTime.Text = mgr.FileCreationTime.ToString();
        }
        catch (Exception ex)
        {

        }
    }
//commented by karthik
    //protected void PopulateClassMethodCoverage(string modName, string nsName, string clsName, string strXMLPath)
    //{
    //    try
    //    {
    //        aggrProxy = new IsimpleWcfClient();
    //        //mgr = aggrProxy.ParseXmlObject();

    //        MtdInfoCollection = aggrProxy.GetMethodInfo(modName, nsName, clsName, strXMLPath);
    //        DataTable dtTable = CreateDataTable(MtdInfoCollection);
    //        Session["MtdDataTable"] = dtTable;
    //        DataView dv = new DataView(dtTable);
    //        dv.Sort = "CovPercentage ASC";
    //        gvClsMtdCovAggregate.DataSource = dv;
    //        gvClsMtdCovAggregate.DataBind();
    //    }
    //    catch (Exception ex)
    //    {
    //    }
    //}
    protected void LoadClsLvlMtdAggReport(string modName, string nsName, string clsName, string strXMLPath)
    {
        try
        {
            aggrProxy = new IsimpleWcfClient();
            //mgr = aggrProxy.ParseXmlObject();

            ClsMtdInfoCollection = aggrProxy.GetClsLvlMethodAggReport(modName, nsName, clsName, strXMLPath);
            gvClsMtdAggReport.DataSource = ClsMtdInfoCollection;
            gvClsMtdAggReport.DataBind();
        }
        catch (Exception ex)
        {
        }
    }
//
    //protected void LoadFileCode(string modName, string nsName, string clsName, string strXMLPath)
    //{
    //    try
    //    {
    //        aggrProxy = new IsimpleWcfClient();
    //        IList<SourceCodeInfo> srcInfoColln = aggrProxy.GetRawSourceCode(modName, nsName, clsName, strXMLPath);
    //        gvSourceCode.DataSource = RemoveCharacters(srcInfoColln);
    //        gvSourceCode.DataBind();

    //    }
    //    catch (Exception ex)
    //    {
    //        string strMsg = ex.Message.ToString().Replace("'", " ");
    //        string strScript = "<script>alert('" + strMsg + "');</script>";
    //        ClientScript.RegisterStartupScript(this.GetType(), "alert", strScript);
    //    }
    //}

    protected IList<SourceCodeInfo> RemoveCharacters(IList<SourceCodeInfo> srcCodeColln)
    {
        IList<SourceCodeInfo> srcCodeCollection = new List<SourceCodeInfo>();
        foreach (SourceCodeInfo sInfo in srcCodeColln)
        {
            SourceCodeInfo sourceInfo = new SourceCodeInfo();
            string strCode = string.Empty;
            sourceInfo.LineNumber = sInfo.LineNumber;
            strCode = sInfo.CodeString.Replace("<", "&lt");
            strCode = strCode.Replace(">", "&gt");
            sourceInfo.CodeString = strCode;
            srcCodeCollection.Add(sourceInfo);
        }
        return srcCodeCollection;
    }

    public string TruncateDouble(double dblValue)
    {
        string strPercent = string.Format("{0:0.##}", dblValue);
        return strPercent + "%";
    }

    public string AddPercentSymbol(string strValue)
    {
        return strValue + "%";
    }

    public int SetLblMajorWidth(double dblValue)
    {
        int major = Convert.ToInt32(Math.Round(dblValue));
        return Convert.ToInt16((major));
    }
    public int SetLblMinorWidth(double dblValue)
    {
        int minor = (100 - (Convert.ToInt32(Math.Round(dblValue))));
        return Convert.ToInt16((minor));
    }
    protected void gvSourceCode_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataRowView drv = e.Row.DataItem as DataRowView;
            Label lblLine = (Label)e.Row.FindControl("lblKey");
            if (ViewState["LnInfoColn"] != null)
            {
                LnInfoColln = ((IList<LineItem>)ViewState["LnInfoColn"]);
            }
            if (!string.IsNullOrEmpty(lblLine.Text))
            {
                foreach (LineItem lInfo in LnInfoColln)
                {
                    if (lInfo.Coverage == 0)
                    {
                        if (lInfo.LnStart == Convert.ToInt16(lblLine.Text) && lInfo.LnEnd == Convert.ToInt16(lblLine.Text))
                        {
                            e.Row.BackColor = System.Drawing.Color.LawnGreen;
                        }
                    }
                    else if (lInfo.Coverage == 1)
                    {
                        if (lInfo.LnStart == Convert.ToInt16(lblLine.Text) && lInfo.LnEnd == Convert.ToInt16(lblLine.Text))
                        {
                            e.Row.BackColor = System.Drawing.Color.DarkCyan;
                        }
                    }
                    else if (lInfo.Coverage == 2)
                    {
                        if (lInfo.LnStart == Convert.ToInt16(lblLine.Text) && lInfo.LnEnd == Convert.ToInt16(lblLine.Text))
                        {
                            e.Row.BackColor = System.Drawing.Color.OrangeRed;
                        }
                    }
                }
            }
        }
    }

    private string GetSortDirection(string column)
    {

        //By default, set the sort direction to ascending.
        string sortDirection = "ASC";

        //Retrieve the last column that was sorted.
        string sortExpression = ViewState["SortExpression"] as string;

        if (sortExpression != null)
        {
            //Check if the same column is being sorted.
            //Otherwise, the default value can be returned.
            if (sortExpression == column)
            {
                string lastDirection = ViewState["SortDirection"] as string;
                if ((lastDirection != null) && (lastDirection == "ASC"))
                {
                    sortDirection = "DESC";
                }
            }
        }

        // Save new values in ViewState.
        ViewState["SortDirection"] = sortDirection;
        showImage = true;
        ViewState["SortExpression"] = column;

        return sortDirection;
    }

    protected void AddSortImage(GridViewRow HeaderRow, int colIndex)
    {
        Image sortImage = new Image();
        sortImage.CssClass = "SortImageStyle";
        //ViewState["SortDirection"] = GetSortDirection(column);
        if (showImage) // this is a boolean variable which should be false 
        {            //  on page load so that image wont show up initially.


            if (ViewState["SortDirection"] != null)
            {
                if (ViewState["SortDirection"].ToString() == "ASC")
                {

                    sortImage.ImageUrl = "/CoverageReport/App_Themes/ReportThemes/images/White_GrayDown.png";
                    sortImage.AlternateText = " Ascending Order";
                }

                else
                {
                    sortImage.ImageUrl = "/CoverageReport/App_Themes/ReportThemes/images/White_GrayUp.png";
                    sortImage.AlternateText = " Descending Order";
                }

                HeaderRow.Cells[colIndex].Controls.Add(sortImage);
            }
        }

    }

    private DataTable CreateDataTable(IList<MethodInfo> mtdInfoColln)
    {
        DataTable dtTable = new DataTable();
        dtTable.Columns.Add("Methodname", typeof(string));
        dtTable.Columns.Add("CovPercentage", typeof(double));
        dtTable.Columns.Add("LineNumber", typeof(int));
        dtTable.Columns.Add("TotalLines", typeof(int));


        foreach (MethodInfo mtdInfo in mtdInfoColln)
        {
            DataRow dtRow = dtTable.NewRow();
            dtRow["Methodname"] = mtdInfo.Methodname;
            dtRow["CovPercentage"] = mtdInfo.CovPercentage;
            dtRow["LineNumber"] = mtdInfo.LineNumber;
            dtRow["TotalLines"] = mtdInfo.TotalLines;

            dtTable.Rows.Add(dtRow);
        }
        return dtTable;
    }

    //protected void gvClsMtdCovAggregate_Sorting(object sender, GridViewSortEventArgs e)
    //{
    //    if (Session["MtdDataTable"] != null)
    //    {
    //        DataTable dtTable = (DataTable)Session["MtdDataTable"];
    //        if (dtTable != null)
    //        {
    //            dtTable.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
    //            gvClsMtdCovAggregate.DataSource = dtTable;
    //            gvClsMtdCovAggregate.DataBind();
    //        }
    //    }
    //}
    //protected void gvClsMtdCovAggregate_RowCreated(object sender, GridViewRowEventArgs e)
    //{
    //    if (e.Row.RowType == DataControlRowType.Header)
    //    //sortColumnIndex = GetSortColumnIndex();
    //    {
    //        string sortExprn = string.Empty;
    //        if (ViewState["SortExpression"] != null)
    //        {
    //            sortExprn = ViewState["SortExpression"].ToString();
    //        }
    //        int index = findColumnIndex(sortExprn);
    //        AddSortImage(e.Row, index);


    //    }

    //}
    //private int findColumnIndex(string accessibleHeaderText)
    //{
    //    for (int index = 0; index < gvClsMtdCovAggregate.Columns.Count; index++)
    //    {
    //        if (String.Compare(gvClsMtdCovAggregate.Columns[index].SortExpression, accessibleHeaderText, true) == 0)
    //        {
    //            return index;
    //        }
    //    }
    //    return -1;
    //}
    //protected void gvClsMtdCovAggregate_RowDataBound(object sender, GridViewRowEventArgs e)
    //{
    //    if (e.Row.RowType == DataControlRowType.DataRow)
    //    {
    //        Label lbl = ((Label)e.Row.FindControl("lbltotcov"));
    //        System.Web.UI.HtmlControls.HtmlTableCell TCell = ((System.Web.UI.HtmlControls.HtmlTableCell)e.Row.FindControl("tdTotCov"));
    //        string[] strArr = null;
    //        if (!string.IsNullOrEmpty(lbl.Text))
    //        {
    //            strArr = lbl.Text.Split('%');
    //            if (Convert.ToDouble(strArr[0].ToString()) < 75.0)
    //            {
    //                TCell.BgColor = "#FF0000";

    //            }
    //        }
    //    }
    //}
    //protected void gvClsMtdCovAggregate_RowCommand(object sender, GridViewCommandEventArgs e)
    //{
    //    switch (e.CommandName)
    //    {
    //        case "Focus":
    //            int rowIndex;
    //            ViewState["LineNumber"] = null;
    //            if (int.TryParse(e.CommandArgument.ToString(), out rowIndex))
    //            {
    //                GridViewRow row = gvClsMtdCovAggregate.Rows[Convert.ToInt16(e.CommandArgument)];
    //                Label lblLine = ((Label)row.FindControl("lblLineNumber"));
    //                for (int i = 0; i <= gvSourceCode.Rows.Count - 1; i++)
    //                {
    //                    GridViewRow rw = gvSourceCode.Rows[i];
    //                    Label lblKey = ((Label)rw.FindControl("lblKey"));
    //                    if (Convert.ToInt16(lblLine.Text) == Convert.ToInt16(lblKey.Text))
    //                    {
    //                        rw.Cells[0].FindControl("lblKey");
    //                        rw.BackColor = System.Drawing.Color.Blue;
    //                        Control c = rw.Cells[0].Controls[0];
    //                        //ScriptManager script = (ScriptManager)Master.FindControl("scripMgr");
    //                        ScriptManager script = ScriptManager.GetCurrent(this.Page);
    //                        if (script != null)
    //                        {
    //                            script.SetFocus(lblStatsName);
    //                        }

    //                    }
    //                }

    //            }
    //            break;
    //    }
    //}
    protected void gvClsMtdAggReport_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            Label lblcov = ((Label)e.Row.FindControl("lbltotcov"));

            System.Web.UI.HtmlControls.HtmlTableCell TCell = ((System.Web.UI.HtmlControls.HtmlTableCell)e.Row.FindControl("totalCover"));
            string[] strArr = null;
            if (!string.IsNullOrEmpty(lblcov.Text))
            {
                strArr = lblcov.Text.Split('%');
                if (Convert.ToDouble(strArr[0].ToString()) < 75.0)
                {
                    TCell.BgColor = "#FF0000";
                }
            }
        }
    }

    protected string TruncateFewCharacters(string MethodName)
    {
        string properString = string.Empty;
        properString = MethodName.Replace("<", "&lt");
        properString = properString.Replace(">", "&gt");
        return WrappableText(properString);
    }
    protected static string WrappableText(string source)
    {
        //string nwln = Environment.NewLine;
        //return "<p>" +
        //    source.Replace(nwln + nwln, "</p><p>")
        //    .Replace(nwln, "<br />") + "</p>";

        if (source.Length > 80)
        {
            string strTemp = source.Substring(0, 80);
            return strTemp;
        }
        else
        {
            return source;
        }
    } 

}
